//
//  AppVersionManager.swift
//  QKYC
//
//  Created by 陈鹏飞 on 2019/4/26.
//  Copyright © 2019 zhan. All rights reserved.
//

import Foundation
import Alamofire
import RxCocoa
import RxSwift
import HandyJSON
open class AppVersionManager: NSObject{
    
    private let disposeBag = DisposeBag()
    ///AppStore的app版本信息
    private var appStoreVersion:String="APPSTOREVERSION"
    
    public static var sharedInstance : AppVersionManager {
        struct Static {
            static let instance : AppVersionManager = AppVersionManager()
        }
        return Static.instance
    }

       ///获取appStore的版本信息
    public func GetAppStoreVersion(withAppleID AppleAppID:String,withIsDebug isDebug:Bool=true,handle: @escaping (((String,String)) -> Void)) {
            AF.request("https://itunes.apple.com/cn/lookup?id=\(AppleAppID)").responseJSON { (response) in
                if isDebug{
                    print("新版本信息~~~~\(response)")
                }
                switch response.result{
                    case .success(let responseTemp):
                        let response = responseTemp as? [String:Any] ?? ["":""]
                        let appStoreModel=AppStoreModel.deserialize(from: response)
                        if (appStoreModel?.results.count)! > 0{
                            handle((appStoreModel?.results[0].version ?? "",appStoreModel?.results[0].releaseNotes ?? ""))
                        }
                    case .failure(let error):
                        if isDebug{
                            print("获取应用市场失败\(error)")
                        }
                }
            }
       }
    
    ///设置AppStore app的版本
    public func SetAppStoreVersion(withVersion version:String)  {
        let userDefaults = UserDefaults.standard
        userDefaults.set(version, forKey: appStoreVersion)
    }
    
    public func GetCurrentAppVersion() -> String {
        // 获取App的版本号
        let userDefaults = UserDefaults.standard
        return userDefaults.string(forKey: appStoreVersion) ?? "0.0.0"
    }
}

open class AppStoreModel: HandyJSON {
    public required init() {
    }
    public var results:[AppStoreResultsModel] = [AppStoreResultsModel]()
}
open class AppStoreResultsModel: HandyJSON {
    public required init() {
    }
    public var version=""
    public var releaseNotes = ""
}
